<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace restful\utils;

class Helper
{
    protected static $snakeCache = [];
    protected static $camelCache = [];
    protected static $studlyCache = [];

    /**
     * 递归实现array_map
     * @param callable $func
     * @param array $array
     * @return array
     */
    public static function arrayMapRecursive(callable $func, array $array): array
    {
        return filter_var($array, FILTER_CALLBACK, ['options' => $func]);
    }

    /**
     * 蛇形(snake_str)
     * @param string $value
     * @param string $delimiter
     * @return mixed|string|string[]|null
     */
    public static function snake(string $value, string $delimiter = '_')
    {
        $key = $value;
        if (isset(static::$snakeCache[$key][$delimiter])) {
            return static::$snakeCache[$key][$delimiter];
        }

        $value = preg_replace_callback('/([A-Z]{1})/', function ($matchs) use ($delimiter) {
            return $delimiter . (strtolower($matchs[0]));
        }, lcfirst($value));

        return static::$snakeCache[$key][$delimiter] = $value;
    }

    /**
     * 转小驼峰(camelStr)
     * @param string $value
     * @param string $delimiter
     * @return string
     */
    public static function camel(string $value, string $delimiter = '_'): string
    {
        if (isset(static::$camelCache[$value])) {
            return static::$camelCache[$value];
        }

        return static::$camelCache[$value] = lcfirst(static::studly($value, $delimiter));
    }

    /**
     * 转大驼峰(StudlyStr)
     * @param string $value
     * @param string $delimiter
     * @return string
     */
    public static function studly(string $value, string $delimiter = '_'): string
    {
        $key = $value;

        if (isset(static::$studlyCache[$key])) {
            return static::$studlyCache[$key];
        }

        $value = str_replace(
            ' ',
            '',
            ucwords(str_replace($delimiter, ' ', $value))
        );

        return static::$studlyCache[$key] = $value;
    }
}